package main

import (
	"code.google.com/p/graphics-go/graphics"
	"fmt"
	z "github.com/nutzam/zgo"
	"image"
	"image/draw"
	"image/png"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

var out = make(chan int)

func main() {
	s1 := time.Now()

	drawable := make(map[string]string)
	drawable["32"] = "drawable-ldpi"
	drawable["48"] = "drawable-mdpi"
	drawable["72"] = "drawable-hdpi"
	drawable["96"] = "drawable-xhdpi"
	drawable["144"] = "drawable-xxhdpi"
	drawable["512"] = ""

	cornerpath := "./corners/"
	iconpath := "./icon.png"
	count := 0

	filepath.Walk(cornerpath, func(path string, f os.FileInfo, e error) error {
		if f == nil {
			return e
		}
		if f.IsDir() {
			return nil
		}
		channel := strings.TrimSuffix(f.Name(), ".png")
		println(fmt.Sprintf("正在处理渠道%s的图标角标", channel))
		for k, v := range drawable {
			savepath := fmt.Sprintf("./save/%s/%s/", channel, v)
			os.MkdirAll(savepath, 0700)
			bounds, _ := strconv.Atoi(k)
			count = count + 1
			go ImageDeal(iconpath, cornerpath+f.Name(), bounds, bounds, savepath, "icon.png")
		}
		return nil
	})
	start := 0
	if count != 0 {
		for {
			start += <-out
			if start == count {
				fmt.Println(time.Now().Sub(s1))
				break
			}
		}
	}
}

func ImageDeal(iconpath string, cornerpath string, width int, height int, savepath string, savename string) {
	_icon, _ := os.Open(iconpath)
	_corner, _ := os.Open(cornerpath)
	icon, _ := png.Decode(_icon)
	corner, _ := png.Decode(_corner)
	defer _icon.Close()
	defer _corner.Close()
	b := icon.Bounds()
	m := image.NewNRGBA(b)
	draw.Draw(m, b, icon, image.ZP, draw.Src)
	draw.Draw(m, corner.Bounds(), corner, image.ZP, draw.Over)
	newimage, _ := os.Create(savepath + savename)
	png.Encode(newimage, m)
	defer newimage.Close()
	src, _ := z.ImagePNG(savepath + savename)
	dst := z.ImageRGBA(width, height)
	graphics.Scale(dst, src)
	z.ImageEncodePNG(savepath+savename, dst)
	out <- 1
}
